package org.hfy.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.hfy.dto.SupplierQueryDTO;
import org.hfy.entity.Supplier;
import org.hfy.mapper.SupplierMapper;
import org.hfy.service.SupplierService;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 供应商Service实现类
 * 
 * @author hfy
 * @version 1.0
 */
@Service
public class SupplierServiceImpl extends ServiceImpl<SupplierMapper, Supplier> implements SupplierService {

    @Override
    public IPage<Supplier> getSupplierPage(SupplierQueryDTO queryDTO) {
        Page<Supplier> page = new Page<>(queryDTO.getCurrent(), queryDTO.getSize());
        return baseMapper.selectSupplierPage(page, queryDTO);
    }

    @Override
    public Supplier getSupplierById(Long id) {
        return this.getById(id);
    }

    @Override
    public boolean addSupplier(Supplier supplier) {
        // 检查供应商代码是否已存在
        if (checkSupplierCodeExists(supplier.getSupplierCode(), null)) {
            throw new RuntimeException("供应商代码已存在");
        }
        
        // 设置默认值
        if (StrUtil.isBlank(supplier.getStatus())) {
            supplier.setStatus("active");
        }
        
        supplier.setCreatedAt(LocalDateTime.now());
        supplier.setUpdatedAt(LocalDateTime.now());
        supplier.setDeleted(false);
        
        return this.save(supplier);
    }

    @Override
    public boolean updateSupplier(Supplier supplier) {
        // 检查供应商代码是否已存在（排除当前记录）
        if (checkSupplierCodeExists(supplier.getSupplierCode(), supplier.getId())) {
            throw new RuntimeException("供应商代码已存在");
        }
        
        supplier.setUpdatedAt(LocalDateTime.now());
        return this.updateById(supplier);
    }

    @Override
    public boolean deleteSupplier(Long id) {
        return this.removeById(id);
    }

    @Override
    public boolean checkSupplierCodeExists(String supplierCode, Long excludeId) {
        QueryWrapper<Supplier> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("supplier_code", supplierCode);
        if (excludeId != null) {
            queryWrapper.ne("id", excludeId);
        }
        return this.count(queryWrapper) > 0;
    }
    
    @Override
    public List<Supplier> getAllSuppliers() {
        QueryWrapper<Supplier> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("deleted", false);
        queryWrapper.orderByAsc("supplier_code");
        return this.list(queryWrapper);
    }
} 